//
//  YLRefreshHeader.swift
//  Swift-Codedase
//
//  Created by xyanl on 2023/9/11.
//
//  普通
import UIKit
import MJRefresh
import Localize_Swift

class YLRefreshHeader: MJRefreshHeader {

    // 标题 左边距
    fileprivate let labelLeftInset: CGFloat = 10
    // 标题
    fileprivate lazy var label: UILabel = {
        let label = UILabel() 
        label.textColor = UIColor(hex: "#6A6A6A")
        label.font = .systemFont(ofSize: 12)
        label.textAlignment = .center
        return label
    }()
    
    fileprivate lazy var loading: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(style: .medium)
        return view
    }() 
    
    
    // 在这里做一些初始化配置（比如添加子控件）
    override func prepare() {
        super.prepare()
        
        // 设置控件的高度
        mj_h = 50
        // 设置自动切换透明度(在导航栏下面自动隐藏)
        isAutomaticallyChangeAlpha = true
        
        addSubview(label)
        addSubview(loading)
    }
    
    // 在这里设置子控件的位置和尺寸
    override func placeSubviews() {
        super.placeSubviews()
        label.bounds = CGRectMake(0, 0, self.label.mj_textWidth(), 16)
        label.center = CGPoint(x: mj_w * 0.5, y: mj_h * 0.5)
        
        loading.center = CGPoint(x: mj_w * 0.5, y: mj_h * 0.5)
        loading.mj_x = label.mj_x - loading.mj_w - labelLeftInset
    }
    
    // 监听scrollView的contentOffset改变
    override func scrollViewContentOffsetDidChange(_ change: [AnyHashable : Any]?) {
        super.scrollViewContentOffsetDidChange(change)
    }
    // 监听scrollView的拖拽状态改变
    override func scrollViewPanStateDidChange(_ change: [AnyHashable : Any]?) {
        super.scrollViewPanStateDidChange(change)
    }
    // 监听scrollView的contentSize改变
    override func scrollViewContentSizeDidChange(_ change: [AnyHashable : Any]?) {
        super.scrollViewContentSizeDidChange(change)
    }
    
    // 监听控件的刷新状态
    override var state: MJRefreshState {
        didSet {
            switch state {
            case .idle: // 普通闲置状态
                label.text = "下拉刷新".localized()
                loading.stopAnimating()
            case .pulling: // 松开就可以进行刷新的状态
                label.text = "松开刷新".localized()
                loading.stopAnimating()
            case .refreshing:
                label.text = "正在刷新".localized()
                loading.startAnimating()
            default: 
                break
            }
        }
    }
    
    // 监听拖拽比例（控件被拖出来的比例）
    override var pullingPercent: CGFloat {
        didSet {
            // xLog("监听拖拽比例: \(pullingPercent)")
            
            // 1.0 0.5 0.0
            // 0.5 0.0 0.5
            // let red = 1.0 - pullingPercent * 0.5
            // let green = 0.5 - 0.5 * pullingPercent
            // let blue = 0.5 * pullingPercent
            // self.label.textColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
        }
    }
    
}
